<template>
  <div class="student-view">
    <el-form :inline="true" class="search-form">
      <el-form-item label="学号">
        <el-input v-model="searchForm.studentNumber" placeholder="请输入学号" clearable />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="班级">
        <el-select
          v-model="searchForm.className"
          placeholder="请选择班级"
          style="width: 200px"
          clearable
        >
          <el-option
            v-for="item in classOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="handleAdd">添加学生</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="studentList" border style="width: 100%">
      <el-table-column prop="studentNumber" label="学号" min-width="16%" />
      <el-table-column prop="name" label="姓名" min-width="16%" />
      <el-table-column label="性别" width="80">
        <template #default="scope">
          {{ scope.row.gender === 0 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="className" label="班级" min-width="16%" />
      <el-table-column prop="major" label="专业" min-width="16%" />
      <el-table-column label="操作" min-width="20%" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加学生弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加学生"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="addForm.studentNumber" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="addForm.gender">
            <el-radio label="男" :value="1">男</el-radio>
            <el-radio label="女" :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="班级" prop="class">
          <el-select v-model="addForm.className" placeholder="请选择班级" style="width: 100%">
            <el-option
              v-for="item in classOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="addForm.major" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import myAxios from "../../../plugins/myAxios.js";
import { useRouter } from 'vue-router'

const router = useRouter()

const searchForm = reactive({
  studentNumber: '', //学号
  name: '',
  className: '' //班级
})

const classOptions = [
  { label: '计科2101', value: '计科2101' },
  { label: '计科2102', value: '计科2102' }
]

const studentList = ref([
  // {
  //   studentId: '2021001',
  //   name: '张三',
  //   gender: '男',
  //   class: '计科2101',
  //   major: '计算机科学与技术',
  //   phone: '13800138000',
  //   email: 'zhangsan@example.com'
  // }
])

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 弹窗显示控制
const dialogVisible = ref(false)
const addFormRef = ref(null)

// 添加表单数据
const addForm = reactive({
  studentNumber: '',
  name: '',
  gender: 0,
  className: '',
  major: '',
  // phone: '',
  // email: ''
})

// 表单验证规则
const rules = {
  // studentId: [
  //   { required: true, message: '请输入学号', trigger: 'blur' },
  //   { pattern: /^\d{7,8}$/, message: '学号格式不正确', trigger: 'blur' }
  // ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  // class: [
  //   { required: true, message: '请选择班级', trigger: 'change' }
  // ],
  // major: [
  //   { required: true, message: '请输入专业', trigger: 'blur' }
  // ],
}

// 获取学生列表数据
const fetchStudentList = async () => {
  try {
    const params = {
      current: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const response = await myAxios.get('/admin/student/list', { params })
    studentList.value = response.records
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取学生列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchStudentList()
}

// 处理重置
const resetSearch = () => {
  searchForm.studentNumber = ''
  searchForm.name = ''
  searchForm.className = ''
  handleSearch()
}

// 处理编辑
const handleEdit = (row) => {
  router.push(`/admin/student/edit/${row.id}`)
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该学生信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await myAxios.post(`/admin/student/delete?id=${row.id}`)
    ElMessage.success('删除成功')
    fetchStudentList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchStudentList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchStudentList()
}

// 处理添加按钮点击
const handleAdd = () => {
  dialogVisible.value = true
  // 重置表单
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 处理弹窗关闭
const handleClose = () => {
  dialogVisible.value = false
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!addFormRef.value) return

  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await myAxios.post('/admin/student/add', addForm)
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchStudentList() // 刷新列表
      } catch (error) {
        ElMessage.error('添加失败')
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchStudentList()
})
</script>

<style scoped>
.student-view {
  margin: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 增加表格内容的样式 */
.el-table {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
